package com.linxiao.framework.activity

import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.LifecycleRegistry
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.linxiao.framework.permission.PermissionManager
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper


/**
 * base activity class of entire project
 *
 * template for activities in the project, used to define common methods of activity
 */
abstract class BaseActivity : AppCompatActivity(), LifecycleOwner {

    private val mReceiver by lazy { ActivityBaseReceiver() }
    private val mCompositeDisposable = CompositeDisposable()
    private var event = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val filter = IntentFilter()
        filter.addAction(ACTION_EXIT_APPLICATION)
        registerReceiver(mReceiver, filter)

        val view = onCreatRootView()
        if(view!=null){
            setContentView(view)
        }

        onInitView(savedInstanceState)
        if(event){
            EventBus.getDefault().register(this)
        }
    }

    override fun onDestroy() {
        PermissionManager.unCallback()
        super.onDestroy()
        unregisterReceiver(mReceiver)
        mCompositeDisposable.clear()
        if (event&&EventBus.getDefault().isRegistered(this)){
            EventBus.getDefault().unregister(this)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        PermissionManager.onSysAlertPermissionResult(this, requestCode)
        PermissionManager.onWriteSysSettingsPermissionResult(this, requestCode)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        PermissionManager.handleCallback(this, requestCode, permissions, grantResults)
    }

    override fun attachBaseContext(newBase: Context) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase))
    }

    protected abstract fun onCreatRootView():View?
    protected abstract fun onInitView(savedInstanceState: Bundle?)

    /**
     * subscribe data which provide by ViewModel
     *
     * observed data will unsubscribe while Activity onStop,
     * for re-subscribe data correctly, suggest perform observe
     * data in method [.onStart]
     */
    fun observe(d: Disposable){
        mCompositeDisposable.add(d)
    }

    fun observe(d:()->Disposable){
        mCompositeDisposable.add(d())
    }

    /**
     * 基础类Activity的BroadcastReceiver
     */
    protected inner class ActivityBaseReceiver : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == ACTION_EXIT_APPLICATION) {
                finish()
            }
        }
    }

    companion object {
        val ACTION_EXIT_APPLICATION = "exit_application"
    }

    fun setEvent(e:Boolean){
        event = e
    }

    /*****************      生命周期感知     ****************************/
    private val lifecycleRegistry by lazy { LifecycleRegistry(this) }

    override fun getLifecycle(): LifecycleRegistry {
        return lifecycleRegistry
    }
}
